//
//  AccountManager.m
//  Module
//
//  Created by Fanty on 13-12-26.
//  Copyright (c) 2013年 Fanty. All rights reserved.
//

#import "AccountManager.h"

#import "DataCenter+Cube.h"
#import <chameleon-ios-sdk/ChamleonSDK.h>

@interface AccountManager()<ZillaDelegate>

-(void)cancelSync;

-(void)syncTimeEvent;
@end


@implementation AccountManager{
    NSTimer* timer;
    Zilla* zilla;
}

-(id)init{
    self=[super init];
    if(self){
        zilla=[[Zilla alloc] initWithZillAccessData:[ZillaAccessData activeSession]];
        zilla.delegate=self;
    }
    return self;
}
- (void)dealloc{
    [self cancelSync];
}

-(void)cancelSync{
    [timer invalidate];
    timer=nil;
    [zilla cancelAllWorkGroup];
}

-(void)syncTimeEvent{
    [self cancelSync];


    [zilla rolePriviligesList:[DataCenter defaultCenter].username];
    
}

-(void)syncAuth:(BOOL)callNow{
    if(callNow){
        [self syncTimeEvent];
    }
    else{
        [self cancelSync];
        timer=[NSTimer scheduledTimerWithTimeInterval:300.0f target:self selector:@selector(syncTimeEvent) userInfo:nil repeats:NO];
        
    }
}

#pragma mark zilla delegate

-(void)rolePriviligesListSuccess:(RolePriviligeModel *)rolePriviligeModel{
    
    [DataCenter defaultCenter].rolePriviligeModel=rolePriviligeModel;
    
    //如果是访客，那么记录一下默认权限
    if([[DataCenter defaultCenter].username isEqualToString:DEFAULT_ACCOUNT_NAME]){
        [DataCenter defaultCenter].guestRolePriviligeModel=rolePriviligeModel;
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CubeAuthSync_Success" object:nil];
    [self syncAuth:NO];
}

-(void)rolePriviligesListFailed:(int)statusCode errorMessage:(NSString *)errorMessage{
    [self syncAuth:NO];

}


@end
